<template>
  <!-- 机构管理页面 -->
  <div>
    <el-row class="caliberHierarchy container">
      <!-- 左侧树 -->
      <el-col :span="6" class="content-right" style="padding-top:10px;padding:0 10px">
        <!-- <upper-template noSearchButton :configIcon="false" style="height:40px;" search-place="left">
          <div slot="buttonArea" class="top-title">
            <span class="vertical-bar"></span>
            机构组织
          </div>
          <div slot="searchArea">
              <onlyOneSearch
                  v-model="filterText"
                  placeholder="请输入名称"
                  :search-method="filterTree"
                ></onlyOneSearch>
          </div>
        </upper-template> -->
        <vp-tree
        :vp-header="{show:true,text:'机构组织',search:true,name:'label'}"
        vp-title="所有机构"
       :filter-node-method="filterNode"
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          @check="handleNodeClick"
          default-expand-all
          show-checkbox
          check-strictly
          ref="configTree"
          node-key="id"
          :expand-on-click-node="false"
          check-on-click-node
        ></vp-tree>
      </el-col>
      <!-- 右侧表  -->
      <el-col style="margin-left:10px;" :span="17" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18">
            <el-button type="primary" @click="addFunc">新增</el-button>
            <el-button type="primary" @click="editFunc">编辑</el-button>
            <el-button type="primary" @click="startOrBackFunc(1)"
              >启用</el-button
            >
            <el-button type="primary" @click="startOrBackFunc(0)"
              >撤销</el-button
            >
          </el-col>
          <el-col :span="6">
            <div class="handleIconBox">
              <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    :model="searchForm"
                    ref="searchForm"
                    label-width="100px"
                    label-position="right"
                    size="mini"
                  >
                    <el-form-item label="机构代码：">
                      <el-input
                        v-model="searchForm.orgCode"
                        style="width:150px"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="机构名称：">
                      <el-input
                        v-model="searchForm.orgName"
                        style="width:150px"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="机构状态：">
                      <el-select
                        v-model="searchForm.status"
                        style="width:150px"
                      >
                        <el-option value="1" label="启用"></el-option>
                        <el-option value="0" label="撤销"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>

                  <div style="text-align:center;padding:10px">
                    <el-button type="primary" size="mini">查询</el-button>
                    <el-button
                      size="mini"
                      @click="
                        (searchForm.orgCode = ''),
                          (searchForm.orgName = ''),
                          (searchForm.status = '')
                      "
                      >重置</el-button
                    >
                  </div>
                </div>
                <i
                  class="iconfont icon-sousuo"
                  title="搜索"
                  slot="reference"
                ></i>
              </el-popover>
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :label="item.label"
                      :key="item.prop"
                      >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                  slot="reference"
                ></i>
              </el-popover>
              <i class="iconfont icon-export" title="导出"></i>
              <i class="iconfont icon-import" title="导入"></i>
            </div>
          </el-col>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @row-click="authorizeFor"
        >
          <el-table-column
            width="55"
            type="selection"
            fixed="left"
          ></el-table-column>
          <el-table-column
            prop="orgCode"
            label="机构代码"
            v-if="columnState[0]"
          >
          </el-table-column>
          <el-table-column
            prop="orgName"
            label="机构名称"
            sortable
            v-if="columnState[1]"
          >
          </el-table-column>
          <el-table-column
            prop="parentOrganName"
            label="上级机构"
            sortable
            v-if="columnState[2]"
          >
          </el-table-column>

          <el-table-column
            prop="status"
            label="机构状态"
            v-if="columnState[3]"
            :filter-method="(val, row) => row.status === val"
            :filters="[
              { text: '启用', value: '1' },
              { text: '注销', value: '0' }
            ]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.status == 1">
                <i class="startState"></i><span>启用</span>
              </div>
              <div v-if="scope.row.status == 0">
                <i class="unStartState"></i><span style="color:red">注销 </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="1"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="10"
          layout="sizes, prev,jumper, next, total"
          :total="400"
        ></el-pagination>
      </el-col>
    </el-row>
    <el-dialog v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      top="2%"
     >
      <el-form
        :model="saveForm"
        ref="addTreeForm"
        label-width="150px"
        label-position="right"
        :rules="saveFormRules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="机构代码：" prop="orgCode" required>
              <el-input
                v-model="saveForm.orgCode"
                style="width:200px"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构名称：" prop="orgName" required>
              <el-input
                v-model="saveForm.roleName"
                style="width:200px"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构层级：" prop="roleDesc">
              <el-select
                v-model="saveForm.mgrRoleId"
                placeholder="请选择"
                style="width:200px"
              >
                <el-option
                  v-for="item in mgrRoleIdList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="上级机构："
              prop="parentOrgCode"
              v-if="saveFlg == 1"
            >
              <el-tooltip
                :content="saveOrgTip"
                :disabled="!saveOrgTip"
                placement="top"
                class="item"
              >
                <el-cascader
                  clearable
                  filterable
                  :options="orgList"
                  v-model="saveForm.parentOrgCode"
                  :props="{
                    checkStrictly: true,
                    emitPath: false,
                    expendTrigger: 'hover'
                  }"
                  :show-all-levels="false"
                  ref="saveOrgTree"
                  style="width:200px"
                  @change="checkFormOrg"
                ></el-cascader>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人：" prop="linkman">
              <el-input
                v-model="saveForm.linkman"
                style="width:200px"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话：" prop="linktel">
              <el-input
                v-model="saveForm.linktel"
                style="width:200px"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构网址：" prop="weburl">
              <el-input
                v-model="saveForm.weburl"
                style="width:200px"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构邮箱：" prop="email">
              <el-input
                v-model="saveForm.email"
                style="width:200px"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮政编码：" prop="zipCode">
              <el-input
                v-model="saveForm.zipCode"
                style="width:200px"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构地址：" prop="orgAddr">
              <el-input
                v-model="saveForm.orgAddr"
                style="width:200px"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构状态：" prop="linktel">
              生效
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构内部层级：" prop="orgDegree">
              <el-select
                v-model="saveForm.orgDegree"
                placeholder="请选择"
                style="width:200px"
              >
                <el-option
                  v-for="item in mgrRoleIdList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="是否部门：" prop="orgDeptFlag">
              <el-select
                v-model="saveForm.orgDeptFlag"
                placeholder="请选择"
                style="width:200px"
              >
                <el-option
                  v-for="item in mgrRoleIdList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="部门类型：" prop="orgType">
              <el-select
                v-model="saveForm.orgType"
                placeholder="请选择"
                style="width:200px"
              >
                <el-option
                  v-for="item in mgrRoleIdList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addOrEdit = false">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { publicManage } from "@/api/index";
import onlyOneSearch from '@/components/onlyOneSearch.vue'

export default {
  components:{
    onlyOneSearch
  },
  data() {
    return {
      filterText: "", // 节点过滤关键字
      userName: "", //右侧用户名
      userDo: "授权角色", // 右侧用户行为
      userDoFlag: 0,
      addOrEdit: false, // 新增/编辑/查看弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: ["新增机构", "编辑机构"],
      // 机构树
      orgList: [
        {
          value: "01",
          label: "一级机构",
          children: [{ value: "001", label: "二级机构" }]
        }
      ],
      // 右侧树data
      treeData: [
        {
          id: 1,
          label: "一级 1",
          children: [
            {
              id: 4,
              label: "二级 1-1",
              children: [
                {
                  id: 9,
                  label: "三级 1-1-1"
                },
                {
                  id: 10,
                  label: "三级 1-1-2"
                }
              ]
            }
          ]
        },
        {
          id: 2,
          label: "一级 2",
          children: [
            {
              id: 5,
              label: "二级 2-1"
            },
            {
              id: 6,
              label: "二级 2-2"
            }
          ]
        },
        {
          id: 3,
          label: "一级 3",
          children: [
            {
              id: 7,
              label: "二级 3-1"
            },
            {
              id: 8,
              label: "二级 3-2"
            }
          ]
        }
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 角色管理下拉框
      mgrRoleIdList: [
        {
          value: "选项1",
          label: "黄金糕"
        },
        {
          value: "选项2",
          label: "双皮奶"
        }
      ],
      // search机构树悬停提示
      searchOrgTip: "",
      // save表单机构树悬停提示
      saveOrgTip: "",
      searchForm: {
        orgName: "",
        ogrCode: "",
        status: "1",
        page: 1,
        size: 10
      },
      saveForm: {
        operateType: "2",
        userId: "",
        userName: "",
        realName: "",
        password: "",
        passwordStr: "",
        orgId: "",
        orgId_text: "",
        useFlag: "",
        empNo: "",
        idcard: "",
        officePhone: "",
        mobilePhone: "",
        famliyPhone: "",
        email: ""
      },
      saveFormRules: {
        userName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        realName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        password: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { min: 6, max: 8, message: "密码长度在6-8之间", trigger: "blur" }
          // { validator: this.validPassword, trigger: "blur" },
        ],
        passwordStr: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { validator: this.validPassword, trigger: "blur" }
        ],
        orgId: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        status: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ]
      },
      checkList: [],
      // 完整表头字段&&列属性配置
      textData: [
        { prop: "roleCode", label: "角色编号" },
        { prop: "roleName", label: "角色名称" },
        { prop: "roleDesc", label: "角色描述 " },
        { prop: "mgrRole", label: "可管理角色" }
      ],
      // 获取table的数据
      tableData: [
        {
          orgType: null,
          orgDegree: null,
          orgId: "40288dfd707fe2ce0170801ecd370013",
          parentId: "4028815d3929aeac013929bf83050001",
          status: "1",
          orgCode: "80000200",
          parentOrganName: "泛鹏银行",
          orgName: "上海分行",
          leafFlag: null,
          orgLevel: 1
        },
        {
          orgType: null,
          orgDegree: null,
          orgId: "40288dfd72220a74017226eb1f3e042f",
          parentId: "40288dfd707fe2ce0170801ecd370013",
          status: "0",
          orgCode: "80000201",
          parentOrganName: "上海分行",
          orgName: "上海支行机构",
          leafFlag: null,
          orgLevel: 2
        }
      ]
    };
  },
  created() {
    this.checkListInit();
    console.log(this.tableData, "模拟数据");
  },
  computed: {
    columnState() {
      console.log(this.checkList);
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    }
  },
  mounted() {
    // this.getList();
  },
  watch: {},
  methods: {
    filterTree() {
      this.$refs.configTree.filter(this.filterText);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 处理save表单机构选中事件
    checkFormOrg() {
      let node = this.$refs.saveOrgTree.getCheckedNodes();
      this.$refs.saveOrgTree.dropDownVisible = false; // 隐藏模态框
      if (node.length != 0) {
        this.saveForm.parentOrganName = node[0].label;
        this.saveOrgTip = node[0].label;
      } else {
        this.saveForm.parentOrganName = "";
        this.saveOrgTip = "";
      }
    },
    // 两个密码校验
    validPassword(rule, value, callback) {
      if (this.saveForm.password === this.saveForm.passwordStr) {
        callback();
      } else {
        callback(new Error("两次输入密码不一致"));
      }
    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row };
      this.saveForm = form;
      this.addOrEdit = true;
    },
    startOrBackFunc(num) {
      let selection = this.$refs.multipleTable.selection;
      let str = num == 1 ? "启用" : "撤销";
      if (selection.length < 1) {
        return this.$message.warning(`请选择要${str}的机构`);
      }
      this.$confirm(`确定要${str}所选机构吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$message.success(str + "成功");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消" + str
          });
        });
    },
    handleNodeClick(obj) {
      // 单选处理
      let node = { ...obj };
      this.$refs.configTree.$tree.setCheckedNodes([]);
      this.$refs.configTree.$tree.setCheckedNodes([node]);
      // console.log("我点了",this.$refs.configTree.$tree)
    },
    caliberProjectNameFormatter(row) {
      return row.caliberProject.caliberProjectName;
    },
    getList() {
      publicManage.query("我的参数").then(res => {
        console.log(res);
      });
    },
    // 点击表格右侧显示为xx授权
    authorizeFor(row) {
      this.$refs.multipleTable.toggleRowSelection(row, true);
      this.userName = row.roleName;
    },
    saveConfigTree() {},
    saveConfigTable() {},
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    }
    // // 增加下级树集
    // addNextTree() {
    //   let node = this.$refs.caliberConfigTree.getCheckedNodes()[0];
    //   if (node.id !== 1) {
    //     return this.$message.warning("请选择根节点");
    //   }
    //   this.isAddNextTree = true;
    // },
    // // 增加下级子叶
    // addNextNode() {
    //   let nodes = this.$refs.caliberConfigTree.getCheckedNodes();
    //   console.log(nodes);
    // },
    // // 删除节点
    // delNode() {
    //   let nodes = this.$refs.caliberConfigTree.getCheckedNodes();
    //   console.log(nodes);
    //   if (nodes.length < 1) {
    //     return this.$message.warning("请选择要删除的节点");
    //   }
    //   this.$confirm("你确认要删除吗？", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning"
    //   })
    //     .then(() => {
    //       this.$message.success("success");
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: "info",
    //         message: "已取消删除"
    //       });
    //     });
    // }
  }
};
</script>

<style lang="scss" scoped>
.top-title {
  
font-size: 14px;
font-family: PingFangSC-Medium, PingFang SC;
font-weight: 500;
color: #000000;
line-height: 20px;
vertical-align: middle;
margin-top: 9px;
}
.vertical-bar {
  line-height: 20px;
}
</style>